package com.brotherly.mpgp;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.brotherly.framework.BaseActivity;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.remoteinterface.RemoteServerService;
import com.brotherly.mpgp.remoteinterface.RemoteServerWatcher;
import com.brotherly.mpgp.view.DownLoadButton;
import com.brotherly.mpgp.view.UpdateFreshListView;
import com.brotherly.mpgp.view.UpdateFreshListView.OnRefreshListener;
import com.brotherly.util.downloader.DownLoaderUtil;

public class GameListActivity extends BaseActivity {

    private DecimalFormat mFileSizeFomat = new DecimalFormat("0.00M");

    class RecommendListAdapter extends BaseAdapter implements OnItemClickListener
    {
        @SuppressWarnings("unused")
        private Context mContext;
        private List<JSONObject> mGameRecommends;
        private LayoutInflater mInflater;

        public RecommendListAdapter(Context context)
        {
            super();
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            return mGameRecommends == null ? 0 : mGameRecommends.size();

        }

        @Override
        public Object getItem(int position)
        {
            if (position < mGameRecommends.size())
            {
                return mGameRecommends.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.main_recommend_list_item, null);
            }

            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            JSONObject gameinfo = (JSONObject) getItem(position);

            try
            {
                String name = gameinfo.getString("name");

                if (gameinfo.has("info"))
                {
                    JSONObject info = gameinfo.getJSONObject("info");
                    if (info.has("players"))
                    {
                        int players = info.getInt("players");

                        ((TextView) convertView.findViewById(R.id.btn_game_tag_2)).setText(players > 999999 ? "999999+"
                                : players
                                        + "");
                    }
                    if (info.has("size"))
                    {
                        int size = info.getInt("size");
                        String fileSizeStr = mFileSizeFomat.format(size / 1024d / 1024d);
                        ((TextView) convertView.findViewById(R.id.btn_game_tag_1)).setText(fileSizeStr);
                    }
                }

                ((TextView) convertView.findViewById(R.id.tv_game_list_item_gamename)).setText(name);

                ImageView icon = ((ImageView) convertView.findViewById(R.id.iv_game_list_item_icon));

                int id = gameinfo.getInt("id");

                String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                        .append("games/blob?key=image&gameref=")
                        .append(id).toString();

                imageViewLoadInternetResource(icon, imageurl, R.drawable.grap_icon);

                String packages = null;
                int fileSize = 0;
                if (gameinfo.has("info"))
                {
                    JSONObject info = gameinfo.getJSONObject("info");
                    try
                    {
                        packages = info.getString("package");
                        fileSize = info.getInt("size");
                    }
                    catch (JSONException e)
                    {
                        Log.d("TAG", "info not packages ");
                    }
                }

                int gameId = gameinfo.getInt("id");
                DownLoadButton dlButton = (DownLoadButton) convertView.findViewById(R.id.dl_button);
                if (packages == null)
                {
                    dlButton.setVisibility(View.INVISIBLE);
                }
                else
                {
                    dlButton.setVisibility(View.VISIBLE);
                    dlButton.setFileSize(fileSize);
                    dlButton.setKey(gameId, name);
                    DownloadEvent event = mDownloadEvents.get(dlButton.getUrl());
                    if (event != null)
                    {
                        if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Info))
                        {
                            int param1 = (Integer) event.param1;
                            if (1 == param1)
                            {
                                JSONObject json = (JSONObject) event.param2;
                                dlButton.setDownLoading();
                                dlButton.setFileSize(json.getInt("fileSize"));
                                dlButton.setComplete(json.getInt("compelete"));
                                dlButton.showProgress();

                                Log.d(dlButton.getUrl(), "Param = 1 FileSize : " + dlButton.getFileSize()
                                        + "    Complete:" + dlButton.getComplete());
                                if (dlButton.getFileSize() <= dlButton.getComplete())
                                {
                                    Log.d(dlButton.getUrl(), "下载完成！");
                                    dlButton.stopDownload();
                                    dlButton.setStatusText();
                                    mDownloadEvents.remove(dlButton.getUrl());
                                }
                            } else if (0 == param1)
                            {
                                dlButton.setPause();
                                dlButton.invalidate();
                            }
                        } else if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Pause))
                        {
                            dlButton.setPause();
                            dlButton.invalidate();
                        } else if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Start))
                        {
                            dlButton.setDownLoading();
                            dlButton.setStatusText();
                        }
                    } else
                    {
                        dlButton.checkLocalFile();
                    }
                }

            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
            convertView.setTag(gameinfo);

            return convertView;
        }

        @Override
        public void notifyDataSetChanged()
        {
            this.mGameRecommends = new ArrayList<JSONObject>(mGames);
            super.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            try
            {
                JSONObject item = (JSONObject) getItem(position - 1);
                if (item != null)
                {
                    Intent intent = new Intent(GameListActivity.this, GameDetailActivity.class);
                    int gameref = item.getInt("id");
                    intent.putExtra("gameref", gameref);
                    if (item.has("identifiers"))
                    {
                        JSONArray identifiers = item.getJSONArray("identifiers");
                        if (identifiers.length() > 0)
                        {
                            intent.putExtra("packageName", identifiers.getString(0));
                            GameListActivity.this.startActivity(intent);
                        }
                    }
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static final int Count_Per_Page = 10;
    private boolean isClear = true;
    private int mIndex;

    private List<JSONObject> mGames;
    private RecommendListAdapter mListAdapter;
    private UpdateFreshListView mListView;
    private HashMap<String, DownloadEvent> mDownloadEvents = new HashMap<String, DownloadEvent>();
    private UpdateFreshListView.OnRefreshListener mRefreshListener = new OnRefreshListener()
    {

        @Override
        public void onLoadMore(UpdateFreshListView listview)
        {
            isClear = false;
            mIndex = mGames.size() / Count_Per_Page;
            gameRecommend();
        }

        @Override
        public void onRefresh(UpdateFreshListView listview)
        {
            isClear = true;
            mIndex = 0;
            gameRecommend();
        }
    };

    private String mTag;

    public void gameRecommend()
    {
        RemoteServerService rss = (RemoteServerService)
                ServiceManager.getInstance().getService(
                        ServiceManager.REMOTESEVER_SERVICE);
        rss.gameRecommend(mTag, mIndex, Count_Per_Page, isClear);
    }

    @Override
    public void onAllReady()
    {
        mDownloadEvents.clear();
        String tag = getIntent().getStringExtra("tag");
        if (mTag == null || !mTag.equals(tag))
        {
            mTag = tag;
            mListView.setIsShowLoadMoreFooter(false);
            mListView.requestFresh();
            ((TextView) findViewById(R.id.tv_title)).setText("游戏分类 - " + mTag);
        } else
        {
            mListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_list);
        mListView = (UpdateFreshListView) findViewById(R.id.lv_game);
        mGames = new LinkedList<JSONObject>();
        mListAdapter = new RecommendListAdapter(this);
        mListView.setAdapter(mListAdapter);
        mListView.setOnItemClickListener(mListAdapter);
        mListView.setOnRefreshListener(mRefreshListener);
        mListView.setIsShowLoadMoreFooter(false);
    }

    @Override
    protected void onServiceEvent(String id, Object param1, Object param2)
    {
        if (RemoteServerService.RemoteServer_Event_RemoteServer_Success.equals(id))
        {
            if (RemoteServerService.ACTION_GAME_RECOMMENDS.equals(param1))
            {
                JSONObject recommendjson = (JSONObject) param2;
                try
                {
                    boolean isClearHistory = recommendjson.getBoolean("isClearHistory");
                    {
                        JSONArray recommends = recommendjson.getJSONArray("body");
                        // mCount = recommendjson.getInt("count");
                        if (isClearHistory)
                        {
                            mGames.clear();
                        }
                        for (int i = 0; i < recommends.length(); i++)
                        {
                            mGames.add(recommends.getJSONObject(i));
                        }
                    }
                    mIndex = mGames.size() / Count_Per_Page;
                    final boolean hasMore = recommendjson.getBoolean("hasMore");
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            mListView.setIsShowLoadMoreFooter(hasMore);
                            mListAdapter.notifyDataSetChanged();
                            mListView.onRefreshComplete();
                            mListView.notifyLoadMoreComplet();
                        }
                    });

                }
                catch (Exception e)
                {}
            }
        } else if (RemoteServerService.RemoteServer_Event_RemoteServer_Error.equals(id))
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    Toast.makeText(GameListActivity.this, "请求失败，请重试.", Toast.LENGTH_SHORT).show();
                }
            });
        } else if (Activity_Event_Internet_Resource_Download_Success.equals(id))
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mListAdapter.notifyDataSetChanged();
                }
            });
        }
        else if (DownLoaderUtil.Activity_Event_FileDownload_Info.equals(id))
        {
            if (1 == (Integer) param1)
            {
                DownloadEvent event = new DownloadEvent();
                event.id = DownLoaderUtil.Activity_Event_FileDownload_Info;
                event.param1 = (Integer) 1;
                event.param2 = param2;
                JSONObject json = (JSONObject) param2;
                String url = json.optString("url", "");
                mDownloadEvents.put(url, event);
                // checkInstallApk(json);
                System.out.println(DownLoaderUtil.Activity_Event_FileDownload_Info);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mListAdapter.notifyDataSetChanged();
                    }
                });

            } else if (-1 == (Integer) param1)
            {
                showSDCardError();
            }
            else if (-2 == (Integer) param1)
            {
                showDownloadLongClick(param2);
            }
            else if (0 == (Integer) param1)
            {
                DownloadEvent event = new DownloadEvent();
                event.id = DownLoaderUtil.Activity_Event_FileDownload_Info;
                event.param1 = param1;
                event.param2 = param2;
                String url = (String) param2;
                mDownloadEvents.put(url, event);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mListAdapter.notifyDataSetChanged();
                        Toast.makeText(GameListActivity.this, "您的网络不给力啊，无法继续下载请调整好了在点我。", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } else if (DownLoaderUtil.Activity_Event_FileDownload_Pause.equals(id))
        {
            String url = (String) param2;
            DownloadEvent event = new DownloadEvent();
            event.id = DownLoaderUtil.Activity_Event_FileDownload_Pause;
            event.param1 = param1;
            event.param2 = param2;
            mDownloadEvents.put(url, event);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mListAdapter.notifyDataSetChanged();
                }
            });
        }
        else if (DownLoaderUtil.Activity_Event_FileDownload_Start.equals(id))
        {
            String url = (String) param2;
            DownloadEvent event = new DownloadEvent();
            event.id = DownLoaderUtil.Activity_Event_FileDownload_Start;
            event.param1 = param1;
            event.param2 = param2;
            mDownloadEvents.put(url, event);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mListAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    private void showSDCardError()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog alertDialog = new AlertDialog.Builder(GameListActivity.this)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.cancel();
                            }
                        }).setMessage("您手机未安装SD，请安装后在使用下载功能。").create();
                alertDialog.show();
            }
        });
    }

    private void showDownloadLongClick(Object param2)
    {
        final Object p2 = param2;
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(GameListActivity.this);
                alertDialog.setTitle("菜单");
                alertDialog.setItems
                        (
                                R.array.downloadmenu, new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        DownLoadButton dlBut = (DownLoadButton) p2;
                                        switch (which)
                                        {
                                            case 0:
                                            {
                                                dlBut.installAPK();
                                                break;
                                            }
                                            case 1:
                                            {
                                                dlBut.deleteDownLoadFile();
                                                break;
                                            }
                                        }
                                    }
                                }
                        );
                alertDialog.show();

            }
        });
    }

}
